package com.jiulan.hearthearing.ui.heart.index;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseVPFragment;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.course.activity.CourseDetailsArticleActivity;
import com.jiulan.hearthearing.ui.course.activity.CourseDetailsFMActivity;
import com.jiulan.hearthearing.ui.course.activity.CourseDetailsLuboActivity;
import com.jiulan.hearthearing.ui.heart.activity.ClassifyActivity;
import com.jiulan.hearthearing.ui.heart.adapter.HeartCourseAdapter;
import com.jiulan.hearthearing.ui.heart.adapter.HeartLiveAdapter;
import com.jiulan.hearthearing.ui.heart.adapter.HeartTotalCourseAdapter;
import com.jiulan.hearthearing.ui.menus.MenuAdapter;
import com.jiulan.hearthearing.ui.heart.model.HeartModel;
import com.jiulan.hearthearing.ui.menus.MenuModel;
import com.jiulan.hearthearing.widget.SpaceItemDecoration;
import com.jiulan.hearthearing.widget.SpaceVerticalItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shehuan.niv.NiceImageView;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 心译通
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public class HeartIndex extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private HeartModel model;
    private MenuAdapter menuAdapter;
    private List<MenuModel> menuModels;
    private HeartLiveAdapter liveAdapter;
    private HeartCourseAdapter courseAdapter;
    private HeartTotalCourseAdapter totalCourseAdapter;

    private View view;
    private SmartRefreshLayout smartLayout;
    private NestedScrollView scrollView;
    private LinearLayout llSearch;
    private XBanner banner;
    private RecyclerView rcvActive;
    private RecyclerView rcvLive;
    private RecyclerView rcvCourse;
    private RecyclerView rcvTotalCourse;
    private TextView tvCheckLive;
    private TextView tvCheckCourse;
    private TextView tvCheckTotalCourse;
    private NiceImageView nivToTop;

    public static HeartIndex newInstance(String content) {
        Bundle arguments = new Bundle();
        arguments.putString("string", content);
        HeartIndex fl = new HeartIndex();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_heart_index, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    private void initView() {
        smartLayout = view.findViewById(R.id.smartLayout);
        scrollView = view.findViewById(R.id.scrollView);
        llSearch = view.findViewById(R.id.llSearch);
        banner = view.findViewById(R.id.banner);
        rcvActive = view.findViewById(R.id.rcvActive);
        rcvLive = view.findViewById(R.id.rcvLive);
        rcvCourse = view.findViewById(R.id.rcvCourse);
        rcvTotalCourse = view.findViewById(R.id.rcvTotalCourse);
        tvCheckLive = view.findViewById(R.id.tvCheckLive);
        tvCheckCourse = view.findViewById(R.id.tvCheckCourse);
        tvCheckTotalCourse = view.findViewById(R.id.tvCheckTotalCourse);
        nivToTop = view.findViewById(R.id.nivToTop);
        llSearch.setOnClickListener(this);
        tvCheckLive.setOnClickListener(this);
        tvCheckCourse.setOnClickListener(this);
        tvCheckTotalCourse.setOnClickListener(this);
        nivToTop.setOnClickListener(this);

        rcvActive.setLayoutManager(new GridLayoutManager(context, 5));

        rcvLive.setLayoutManager(new LinearLayoutManager(context));
        rcvLive.addItemDecoration(new SpaceVerticalItemDecoration(context, R.dimen.dp_6));

        rcvCourse.setLayoutManager(new GridLayoutManager(context, 2));
        rcvCourse.addItemDecoration(new SpaceItemDecoration(getResources().getDimensionPixelSize(R.dimen.dp_10), SpaceItemDecoration.GRIDLAYOUT));

        rcvTotalCourse.setLayoutManager(new LinearLayoutManager(context));
        rcvTotalCourse.addItemDecoration(new SpaceVerticalItemDecoration(context, R.dimen.fab_margin));
        smartLayout.setEnableLoadMore(false);
        smartLayout.setEnableNestedScroll(true);
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData(null);
                    }
                }, 1000);
            }
        });
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > oldScrollY) {//下滑
                    nivToTop.setVisibility(View.VISIBLE);
                }
                if (scrollY < oldScrollY) {//上滑

                }
                if (scrollY == 0) {//滑倒顶部
                    nivToTop.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
    }

    private void getData(String loadingMsg) {
        HashMap hashMap = new HashMap();
        new HttpRequest(context).doGet(UrlConstants.heart_index, loadingMsg, hashMap, HeartModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                smartLayout.finishRefresh();
                if (result instanceof HeartModel) {
                    model = (HeartModel) result;
                    setBanner();
                    setMenus();
                    setLiveBroadcast();
                    setCourse();
                    setTotalCourse();
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void setTotalCourse() {
        totalCourseAdapter = new HeartTotalCourseAdapter(model.getData().getClass_book());
        rcvTotalCourse.setAdapter(totalCourseAdapter);
        totalCourseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (model.getData().getClass_book().get(position).getType()) {
                    case 0:
                        CourseDetailsLuboActivity.actionStart(context, model.getData().getClass_book().get(position).getId());
                        break;
                    case 1:
                        break;
                    case 2:
                        CourseDetailsFMActivity.actionStart(context, model.getData().getClass_book().get(position).getId());
                        break;
                    case 3:
                        CourseDetailsArticleActivity.actionStart(context, model.getData().getClass_book().get(position).getId());
                        break;
                }
            }
        });
    }

    private void setCourse() {
        courseAdapter = new HeartCourseAdapter(model.getData().getClass_video());
        rcvCourse.setAdapter(courseAdapter);
        courseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CourseDetailsLuboActivity.actionStart(context, model.getData().getClass_video().get(position).getId());
            }
        });
    }

    private void setLiveBroadcast() {
        liveAdapter = new HeartLiveAdapter(model.getData().getClass_live());
        rcvLive.setAdapter(liveAdapter);
    }

    /**
     * banner
     */
    private void setBanner() {
        if (model.getData().getBanner().size() > 0) {
            banner.setVisibility(View.VISIBLE);
            banner.setBannerData(model.getData().getBanner());
            //设置广告图片点击事件
            banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                @Override
                public void onItemClick(XBanner banner, Object model, View view, int position) {
                    Toast.makeText(context, "点击了第" + (position + 1) + "图片", Toast.LENGTH_SHORT).show();
                }
            });
            //加载广告图片
            banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object object, View view, int position) {
                    //在此处使用图片加载框架加载图片，demo中使用glide加载，可替换成自己项目中的图片加载框架
                    Glide.with(context).load(model.getData().getBanner().get(position).getXBannerUrl()).placeholder(R.mipmap.union_banner).error(R.mipmap.union_banner).into((ImageView) view);
                }
            });
        } else {
            banner.setVisibility(View.GONE);
            Toast.makeText(context, "获取广告数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setMenus() {
        menuModels = new ArrayList<>();
        menuModels.add(new MenuModel(R.mipmap.heart_gongkaike, "公开课FM"));
        menuModels.add(new MenuModel(R.mipmap.heart_zhibo, "直播课程"));
        menuModels.add(new MenuModel(R.mipmap.heart_mingshilubo, "名师录播"));
        menuModels.add(new MenuModel(R.mipmap.heart_jingxuanwenzhang, "精选文章"));
        menuModels.add(new MenuModel(R.mipmap.heart_classify, "全部分类"));
        menuAdapter = new MenuAdapter(menuModels);
        rcvActive.setAdapter(menuAdapter);
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (menuModels.get(position).getActiveName()) {
                    case "公开课FM":
                        ClassifyActivity.actionStart(context, 0);
                        break;
                    case "直播课程":
                        ClassifyActivity.actionStart(context, 1);
                        break;
                    case "名师录播":
                        ClassifyActivity.actionStart(context, 2);
                        break;
                    case "精选文章":
                        ClassifyActivity.actionStart(context, 3);
                        break;
                    case "全部分类":
                        ClassifyActivity.actionStart(context, 4);
                        break;
                }
            }
        });
    }

    @Override
    protected void onFragmentFirstVisible() {
        smartLayout.autoRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCheckLive:
                ClassifyActivity.actionStart(context, 1);
                break;
            case R.id.tvCheckCourse:
                ClassifyActivity.actionStart(context, 2);
                break;
            case R.id.tvCheckTotalCourse:
                ClassifyActivity.actionStart(context, 4);
                break;
            case R.id.nivToTop:
                scrollView.fling(0);
                scrollView.smoothScrollTo(0, 0);
                break;
        }
    }
}
